package com.coderman.common.starter.nacos.paperwork.service;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 * date: 2020/10/12
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class ConfigDataHelperService {

    private static ConcurrentHashMap<String,String> concurrentHashMap = new ConcurrentHashMap<>();

    /**
     * 将数据存入map容器中
     * @param dataId
     * @param groupId
     * @param content
     */
    public void addConfig(String dataId,String groupId,String content){
        String key = dataId+"-"+groupId;
        concurrentHashMap.put(key,content);
    }

    /**
     * 根据dataId 和 groupId获取配置内容
     * @param dataId
     * @param groupId
     * @return
     */
    private String getConfig(String dataId,String groupId){
        String key = dataId+"-"+groupId;
        return concurrentHashMap.get(key);
    }

    /**
     *
     * @param dataId
     * @param groupId
     * @param varMap
     * @return
     */
    public String getNewConfig(String dataId, String groupId, Map<String,String> varMap){
        String contentTemplate = getConfig(dataId,groupId);
        return getNewConfig(contentTemplate,varMap);
    }

    /**
     * 进行文本占位符替换
     * @param template
     * @param varMap
     * @return
     */
    private String getNewConfig(String template ,Map<String,String> varMap ){
        String temp = template;
        if(varMap == null || varMap.isEmpty()){
            return template;
        }
        for (Map.Entry<String,String> entry : varMap.entrySet()){
            String key = "\\$\\{"+entry.getKey()+"\\}";
            temp = temp.replaceAll(key,entry.getValue());
        }
        return temp;
    }

}
